package com.endava.action;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;

public class ForwardRequestToJSPAction extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        String action = req.getParameter("action");
        boolean useRedirect = req.getParameter("redirect") != null;
        if (action == null || action.isEmpty()) {
            Writer writer = null;
            try {
                writer = res.getWriter();
                writer.write("Please provide us the action...");
            } catch (IOException e) {
                System.out.println("Exception: " + e.getMessage());
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException e) {
                    System.out.println("Error on closing the writer");
                }
            }
        } else {
            if (!useRedirect) {

                HttpSession session = req.getSession();
                System.out.println("session.isNew(): " + session.isNew());
                session.setAttribute("action", action);
                RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/pages/session.jsp");
                requestDispatcher.forward(req, res);

//                req.setAttribute("action", action);
//                RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/pages/action.jsp");
//                requestDispatcher.forward(req, res);


            } else {
                res.sendRedirect("http://www.yahoo.com");
            }
        }
    }
}
